#include <iostream>
#include <pthread.h>
#include <vector>
#include <string>
#include <queue>
#include <unistd.h>

using namespace std;

struct ThreadInfo
{
    pthread_t tid;
    string name;
};

template <class T>
class ThreadPool
{
    static const int defaultnum = 5;
public:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void Sleep()
    {
        pthread_cond_wait(&_cond,&_mutex);
    }

    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }
    string GetThreadName(pthread_t tid)
    {
        for(auto e : _threads)
        {
            if(tid == e.tid)
                return e.name;
        }
        return "";
    }

public:
    static void* HandlerTask(void* args)
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
        string name = tp->GetThreadName(pthread_self());
        while(true)
        {
            tp->Lock();
            while(tp->IsQueueEmpty())
            {
                tp->Sleep();
            }
            T t = tp->Pop();
            tp->Unlock();
            t.run(); // 每个任务线程私有,不用加锁
            cout << name << " run, result: " << t.GetResult() << endl;
        }
    }
    T Pop()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
    void push(const T& t)
    {   
        Lock();

        _tasks.push(t);
        // 唤醒线程
        Wakeup();
        Unlock();
    }
    void start()
    {
        int num = defaultnum;
        for (int i = 0; i < num; i++)
        {
            _threads[i].name = "thread-" + to_string(i + 1);
            pthread_create(&(_threads[i].tid), nullptr, HandlerTask, this);
        }
    } 
    static ThreadPool<T>* GetInstance()
    {
        if(_tp == nullptr)// 双重判定空指针, 降低锁冲突的概率, 提高性能
        {
            pthread_mutex_lock(&_lock);// 使用互斥锁, 保证多线程情况下也只调用一次 new.
            if(_tp == nullptr)
            {
                cout << "log singleton create done first!" << endl;
                _tp = new ThreadPool<T>;
            }
            pthread_mutex_unlock(&_lock);
        }
        return _tp;
    }
private:
    ThreadPool(int num = defaultnum)
        : _threads(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ThreadPool(const ThreadPool<T>& t) = delete;
    const ThreadPool<T>& operator=(const ThreadPool<T>& t) = delete;
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
private:
    vector<ThreadInfo> _threads;
    queue<T> _tasks;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T>* _tp; //懒汉
    static pthread_mutex_t _lock; //锁
};

template <class T>
ThreadPool<T>* ThreadPool<T>::_tp = nullptr; //类外面定义
template <class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;